var express = require('express');
var router = express.Router();
const moment = require('moment');
const AccountModel = require('../../models/AccountModel');
//console.log(moment('2023-02-24').toDate())//.toDate()可以将对象转成日期对象
//格式化日期对象
//moment(new Date())会创建一个属于自己的对象
//console.log(moment(new Date()).format('YYYY-MM-DD'))
//导入中间件检测登录
let checkloginMiddleware = require('../../middlewares/checkloginMiddleware');
//记账本列表
router.get('/account',checkloginMiddleware, function(req, res, next) {
  //判断
  if(!req.session.username){
    return res.redirect('/login')
  }
  AccountModel.find().sort({time:-1}).then((data)=>{
    res.render('list',{accounts:data,moment:moment});
  }).catch((result)=>{
    res.status(500).send('读取失败~~');
    return;
  })
});
//添加记录
router.get('/account/create',checkloginMiddleware, function(req, res, next) {
  res.render('create');
});
//新增记录
router.post('/account',checkloginMiddleware,(req,res)=>{
  //获取请求体数据
  console.log(req.body);
  //新time覆盖旧time
  AccountModel.create({...req.body,time:moment(req.body.time).toDate()}).then((data)=>{
    res.render('success',{msg:'添加成功',url:'/account'})
  }).catch((result)=>{
    res.status(500).send('插入失败');
    return;
  })
})
//删除记录
router.get('/account/:id',checkloginMiddleware,(req,res)=>{
  //获取params的id参数
  let id = req.params.id;
  //删除
  AccountModel.deleteOne({_id:id}).then((data)=>{
    //提醒
    res.render('success',{msg:'删除成功~',url:'/account'});
  }).catch((result)=>{
    res.status(500).send('删除失败');
    return;
  })
})
module.exports = router;
